package com.wangcanxuan.www.util;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务工具类
 *
 * @author HHLJ
 * @date 2022/03/27
 */
public class TransactionUtil {
    private TransactionUtil() {
    }


    /**
     * 事务开始
     *
     * @param connection 连接
     * @throws SQLException sqlexception异常
     */
    public static void transactionBegin(Connection connection) throws SQLException {
        if (ValidateUtil.isNull(connection)) {
            return;
        }
        if (connection.getAutoCommit()) {
            connection.setAutoCommit(false);
        }
    }


    /**
     * 事务结束
     *
     * @param connection 连接
     * @throws SQLException sqlexception异常
     */
    public static void transactionEnd(Connection connection) throws SQLException {
        if (ValidateUtil.isNull(connection)) {
            return;
        }
        if (!connection.getAutoCommit()) {
            connection.setAutoCommit(true);
        }
    }

    /**
     * 事务提交
     *
     * @param connection 连接
     * @throws SQLException sqlexception异常
     */
    public static void transactionCommit(Connection connection) throws SQLException {
        if (ValidateUtil.isNull(connection)) {
            return;
        }
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    }

    /**
     * 事务回滚
     *
     * @param connection 连接
     * @throws SQLException sqlexception异常
     */
    public static void transactionRollback(Connection connection) throws SQLException {
        if (ValidateUtil.isNull(connection)) {
            return;
        }
        if (!connection.getAutoCommit()) {
            connection.rollback();
        }
    }

    /**
     * 得到事务连接
     *
     * @return {@link Connection}
     */
    public static Connection getTransactionConnection() {
        return ConnectionPoolUtil.getInstance().getTransactionConnection();
    }

    /**
     * 返回事务连接
     */
    public static void returnTransactionConnection() {
        ConnectionPoolUtil.getInstance().returnTransactionConnection();
    }
}
